package com.smartstate.iot.service;

import com.smartstate.iot.config.redis.RedisService;
import com.smartstate.iot.entity.TopicConfig;
import com.smartstate.iot.entity.TopicLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Component
public class TypeScheduleTask {
    @Autowired
    private TopicService topicService;
    @Resource
    private TopicLogService logService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisService redisService;

    /**
     * 每10秒从数据库读取一次最新信息，如果该信息为10秒之前，将该设备设置为离线
     */
    @Scheduled(cron = "0/10 * * * * ? ")
    public void judgeState() {
        List<TopicConfig> topicConfigs = topicService.getNormalBoxes();
        long time = new Date().getTime();
        for (TopicConfig topicConfig : topicConfigs) {
            if ((time - Long.parseLong(topicConfig.getTimesTamps())) > 20 * 1000L) {
                log.info(topicConfig.getDeviceName()+"设备离线,数据清楚开始!");
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                TopicLog topicLog = new TopicLog();
                topicLog.setDeviceId(topicConfig.getDeviceId());
                topicLog.setLogName(topicConfig.getDeviceName());
                topicLog.setType("离线");
                topicLog.setDate(simpleDateFormat.format(time));
                topicLog.setDetail("设备状态离线");
                logService.save(topicLog);
                //  将redis中的数据归0
                Set keys = redisTemplate.keys(topicConfig.getDeviceId() + ":*");
                Iterator iterator = keys.iterator();
                while (iterator.hasNext()) {
                    String next = (String) iterator.next();
                    Map<String, Object> cacheMap = redisService.getCacheMap(next);
                    for (Map.Entry<String, Object> stringObjectEntry : cacheMap.entrySet()) {
                        if ("ip".equals(stringObjectEntry.getKey())||"port".equals(stringObjectEntry.getKey())){
                            continue;
                        }
                        stringObjectEntry.setValue("0.00");
                    }
                    redisService.setCacheMap(next, cacheMap);
                    int index = next.lastIndexOf(":");
                    String substring = next.substring(index + 1);
                    redisService.setCacheMap(substring, cacheMap);
                }

                log.info(topicConfig.getDeviceName()+"设备离线,数据清除完成!");
            }
        }
    }
}
